package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.ApartmentInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {



    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private DistrictInfoService districtInfoService;

    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private RoomInfoService roomInfoService;

    @Override//分页查询接口
    public void customPage(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customSelectPage(page,queryVo);

    }

    @Override//保存更新接口
    public void customSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        //判断是保存还是更新，有id是更新，没有id是保存
        boolean isUpdate = apartmentSubmitVo.getId() != null;
        //2.调用mybatis-plus.service.保存和更新的方法
        //需要添加回显的省市区，因为前端只给了id
        Long provinceId = apartmentSubmitVo.getProvinceId();//获取省份ID
        ProvinceInfo provinceInfo = provinceInfoService.getById(provinceId);//根据省份id获取省份对象
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());
        CityInfo cityInfo = cityInfoService.getById(apartmentSubmitVo.getCityId());
        apartmentSubmitVo.setCityName(cityInfo.getName());
        DistrictInfo districtInfo = districtInfoService.getById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());

        // 保存或更新公寓主表
        saveOrUpdate(apartmentSubmitVo);

        //3.如果是更新，需要先删除里面的数据在增加数据
        if (isUpdate) {
            //删除图片
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper= new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,apartmentSubmitVo.getId());
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphInfoLambdaQueryWrapper);
            //删除配套
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper=new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
            //删除标签
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper=new LambdaQueryWrapper<>();
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,apartmentSubmitVo.getId());
            apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
            //删除杂费
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper=new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        }

        //4.最终一定要重新插入中间表的关联数据 注意：图片类型本次固定是公寓
        //图片的保存
        //从提交的表单对象`apartmentSubmitVo`中获取图片列表。这个列表包含了前端上传的多张图片的信息（比如图片名称、URL等
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        //判断图片列表是否非空。如果列表不为空且至少有一个元素，则执行括号内的逻辑；否则跳过
        if (!CollectionUtils.isEmpty(graphVoList)){
            //创建一个`GraphInfo`类型的ArrayList，初始容量设置为前端传来的图片列表的大小。这样避免在添加元素时多次扩容，提高效率
            List<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            // 遍历前端传来的每一个图片VO对象（GraphVo）
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();//创建一个新的图片实体对象。
                graphInfo.setName(graphVo.getName());//将VO中的图片名称设置到实体对象。
                graphInfo.setUrl(graphVo.getUrl());//将VO中的图片URL设置到实体对象。
                graphInfo.setItemId(apartmentSubmitVo.getId());//设置这个图片关联的公寓ID（即当前正在操作的公寓ID）
                graphInfo.setItemType(ItemType.APARTMENT);//设置图片关联的项目类型为公寓
                graphInfoList.add(graphInfo);//将构建好的`GraphInfo`实体对象添加到列表中
            }
            graphInfoService.saveBatch(graphInfoList);//使用Service的批量保存方法，将整个`graphInfoList`一次性保存到数据库
        }
        //公寓配套保存
        //在Java对象 `apartmentSubmitVo` 中，`getFacilityInfoIds()`
        // 方法返回的就是 `List<Long>`，所以遍历时得到的每个 `facilityInfoId` 已经是Long类型的设施ID。
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            List<ApartmentFacility> apartmentFacilityList=new ArrayList<>(facilityInfoIds.size());
            //每个元素 facilityInfoId 已经是设施表的 ID 值（Long 类型）
            for (Long facilityInfoId : facilityInfoIds) {
                //这里使用了建造者模式（Builder Pattern）来构建对象。分解如下：
                //- `ApartmentFacility.builder()`：创建一个建造者对象
                //com\atguigu\lease\model\entity\ApartmentFacility.java公寓配套表需要这两个属性：apartment_id和facility_id
                //- `.facilityId(facilityInfoId)`：设置配套设施的ID
                //- `.apartmentId(apartmentSubmitVo.getId())`：设置公寓的ID（这个ID是在前面保存主表时生成的）
                //- `.build()`：构造最终的`ApartmentFacility`对象
                ApartmentFacility apartmentFacility = ApartmentFacility
                        .builder()
                        .facilityId(facilityInfoId)
                        .apartmentId(apartmentSubmitVo.getId())
                        .build();
                apartmentFacilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }
        //公寓标签保存
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)) {
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().labelId(labelId)
                        .apartmentId(apartmentSubmitVo.getId()).build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        //公寓杂费值
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            List<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().feeValueId(feeValueId)
                        .apartmentId(apartmentSubmitVo.getId()).build();
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }
    }

    @Override//根据id获取公寓详细信息，用于修改页面回显
    public ApartmentDetailVo customGetById(Long id) {
        return apartmentInfoMapper.customSelectById(id);
    }

    @Override
    public void customRemoveById(Long id) {
        //要删除之前需要判断公寓里面是否存在房间
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(roomInfoLambdaQueryWrapper);
        if (count>0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        //删除中间表
        //删除图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper= new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);
        //删除配套
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper=new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
        //删除标签
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper=new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
        //删除杂费
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper=new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);

        removeById(id);
    }

}





